package com.demo.wechat.controller;

import cn.hutool.core.lang.UUID;
import com.demo.wechat.config.WeChatOAuthProperties;
import com.demo.wechat.dto.WeChatLoginUrlResponse;
import com.demo.wechat.dto.WeChatTokenResponse;
import com.demo.wechat.dto.WeChatUserInfo;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
public class WeChatAuthController {

    private final WeChatOAuthProperties weChatOAuthProperties;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;


    //@Value("${frontend.url}")
    //private String frontendUrl;

    @GetMapping("/wechat/callback")
    public ResponseEntity<?> wechatCallback(
            @RequestParam("code") String code,
            @RequestParam(value = "state", required = false) String state) {

        // 使用配置的属性
        String tokenUrl = String.format(
                "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                weChatOAuthProperties.getAppId(),
                weChatOAuthProperties.getAppSecret(),
                code);

        try {
            // 2. 调用微信API
            ResponseEntity<String> response = restTemplate.getForEntity(tokenUrl, String.class);
            WeChatTokenResponse tokenResponse = objectMapper.readValue(response.getBody(), WeChatTokenResponse.class);

            // 3. 获取用户信息
            String userInfoUrl = String.format(
                    "https://api.weixin.qq.com/sns/userinfo?" +
                            "access_token=%s&openid=%s",
                    tokenResponse.getAccessToken(), tokenResponse.getOpenId());

            ResponseEntity<String> userResponse = restTemplate.getForEntity(userInfoUrl, String.class);
            WeChatUserInfo userInfo = objectMapper.readValue(userResponse.getBody(), WeChatUserInfo.class);
            String nickname = new String(userInfo.getNickname().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            System.out.println(nickname);
            userInfo.setNickname(nickname);
            System.out.println(userInfo);
            // TODO
            // 4. 处理用户登录/注册逻辑
            //User user = userService.findOrCreateByWeChat(userInfo);

            // 5. 生成自己的JWT token或session
            //String jwtToken = jwtService.generateToken(user);

            // 6. 重定向到前端
            return null;
            /*return ResponseEntity.status(HttpStatus.FOUND)
                    .header(HttpHeaders.LOCATION, frontendUrl + "?token=" + "This is the place where the token is")
                    .build();*/
        } catch (Exception e) {
            throw new RuntimeException("微信登录处理失败", e);
        }
    }

    @GetMapping("/wechat/login-url")
    public ResponseEntity<WeChatLoginUrlResponse> getWeChatLoginUrl() {
        try {
            String state = UUID.randomUUID().toString(); // 使用随机state增强安全性

            String url = "https://open.weixin.qq.com/connect/qrconnect?" +
                    "appid=" + weChatOAuthProperties.getAppId() +
                    "&redirect_uri=" + URLEncoder.encode(weChatOAuthProperties.getRedirectUri(), StandardCharsets.UTF_8.name()) +
                    "&response_type=code" +
                    "&scope=" + weChatOAuthProperties.getScope() +
                    "&state=" + state +
                    "#wechat_redirect";

            return ResponseEntity.ok(new WeChatLoginUrlResponse(url, state));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("生成微信登录URL失败", e);
        }
    }
}
